package com.grp6.game.ui.platform.swing;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

import com.grp6.game.ui.platform.IDialog;
import com.grp6.game.ui.platform.IQuestionValidator;

public class SwingDialog implements IDialog {
	private static final long serialVersionUID = 1L;
	private ArrayList<QuestionStruct> questionaire = new ArrayList<QuestionStruct>();
	
	private JFrame parent;
	private JDialog dialog;
	private JButton okButton;
	private GridLayout layout;
	private int rows = 1;
	
	public SwingDialog(JFrame frame){
		parent = frame;
		dialog = new JDialog(parent,true);
		layout = new GridLayout();
		layout.setColumns(2);
		dialog.setLayout(layout);
		dialog.setSize(500, 70);
		okButton = new JButton("OK");
		okButton.setEnabled(false);
		okButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				dialog.setVisible(false);
			}
		});
	}
	
	

	@Override
	public void addQuestions(String question, IQuestionValidator validator) {
		QuestionStruct struct = new QuestionStruct(question, validator);
		layout.setRows(++rows);
		dialog.add(struct.label);
		dialog.add(struct.textField);
		Dimension size = dialog.getSize();
		dialog.setSize((int)size.getWidth(),(int)size.getHeight()+30);
		questionaire.add(struct);
	}

	@Override
	public void display() {
		dialog.add(new JLabel(" "));
		dialog.add(okButton);
		dialog.setVisible(true);
	}
	
	private class QuestionStruct{
		private JLabel label;
		private String answer;
		private JTextField textField;
		private boolean valid;
		private QuestionStruct(final String question,final IQuestionValidator validator){
			label = new JLabel(question);
			textField = new javax.swing.JTextField();
			textField.addCaretListener(new CaretListener() {
				@Override
				public void caretUpdate(CaretEvent e) {
					answer = textField.getText();
					valid = validator.isValid(question, answer);
					for(QuestionStruct q: questionaire)
						if (q.valid==false){
							okButton.setEnabled(false);
							return;
						}
					okButton.setEnabled(true);
				}
			});
		}
	}

}
